//
//  NSString+Additions.m
//  Compression
//
//  Created by David Aspinall on 13/05/08.
//  Copyright 2008 Ticoon Technology. All rights reserved.
//

#import "NSString+Additions.h"
#import "NSData+Additions.h"

#import <sys/sysctl.h>

@implementation NSString (Additions)

+ (BOOL)IsEmpty:(NSString *)str;
{
	if (str == NULL)
		return (YES);
	
	return [str isEmpty];
}

+ (NSString *)stringWithUUID;
{
	CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault); 
	CFStringRef stringRef = CFUUIDCreateString(kCFAllocatorDefault, uuidRef); 
	CFRelease(uuidRef); 
	
	return [(id)stringRef autorelease]; 
}

- (NSString *)md5Hash
{
	NSString *hash = nil;
	NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
	if (data != nil)
	{	
		hash = [[data md5Digest] hexStringValue];
	}
	return hash;
}

- (NSString *)trimWhiteSpace 
{
	NSMutableString *s = [[self mutableCopy] autorelease];
	CFStringTrimWhitespace ((CFMutableStringRef) s);
	return (NSString *) [[s copy] autorelease];
}

- (BOOL)isEmpty 
{
	return ([self length] == 0);
}

- (NSString *)stringByAppendingElipsisAfterCharacters:(int)count 
{
	if ([self length] <= count) 
		return self;

	return [[self substringToIndex:count] stringByAppendingString:@"..."];
}

+ (NSString *)hardwareModel
{
	size_t size;
	sysctlbyname("hw.model", NULL, &size, NULL, 0);
	char *machine = malloc(size);
	sysctlbyname("hw.model", machine, &size, NULL, 0);
	NSString *platform = [NSString stringWithCString:machine];
	free(machine);
	return platform;
}  


+ (NSString *)hardwareCPU
{
	size_t size;
	sysctlbyname("hw.machine", NULL, &size, NULL, 0);
	char *machine = malloc(size);
	sysctlbyname("hw.machine", machine, &size, NULL, 0);
	NSString *platform = [NSString stringWithCString:machine];
	free(machine);
	return platform;
}  


#if !TARGET_OS_IPHONE
/* NSCalendarDate is not on iPhone OS 2.2 */
+ (NSString *)stringWithHTTPFormattedDate:(NSCalendarDate *)date
{
	NSString *formatted = nil;
	
	if ( date != nil )
	{
		// Returns a formatter for dates in HTTP format (i.e. RFC 822, updated by RFC 1123).
		// e.g. "Sun, 06 Nov 1994 08:49:37 GMT"
		NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
		
		[dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
		[dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss GMT"];
		
		formatted = [dateFormatter stringFromDate:date];
	}
	return formatted;
}
#endif
@end
